package udp.dictionary_service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 * 这里客户端作为发送端
 **/
public class Client {

    public static void main(String[] args) throws IOException {
        //目前服务器在本地，ip地址就是127.0.0.1
        //目前服务器的端口是8080

        DatagramSocket socket = new DatagramSocket(9999);//端口绑定一次就够了，提到while循环外面
        //目前只发送一次请求
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {

        String word = scanner.nextLine();
        //准备发送请求
        String request = "我是Java19班的\r\n" + word + "\r\n";
        byte[] bytes = request.getBytes("UTF-8");
        DatagramPacket sent = new DatagramPacket(
                bytes,
                0,
                bytes.length,
                InetAddress.getLoopbackAddress(),
                8080
        );
        socket.send(sent);//请求发过去

        //接收方去接收数据
        byte[] buf = new byte[1024];
        DatagramPacket received = new DatagramPacket(buf, buf.length);


        socket.receive(received);//阻塞在这里，等响应过来接收响应
        int n = received.getLength();
        String response = new String(buf, 0, n, "UTF-8");
        System.out.println(response);
    }



    }
}
